use std::error::Error;
use std::fs::File;
use std::io::{self, Read};

pub fn learn_error() {
  _learn_error0();
  _learn_opt();
}

fn _read_username_from_file() -> Result<String, io::Error> {
  let username_file_result = File::open("hello.txt");
  let mut username_file = match username_file_result {
    Ok(file) => file,
    Err(e) => return Err(e),
  };
  let mut username = String::new();
  match username_file.read_to_string(&mut username) {
    Ok(_) => Ok(username),
    Err(e) => Err(e),
  }
}

fn _read_username_from_file0() -> Result<String, io::Error> {
  let mut username_file = File::open("hello.txt")?;
  let mut username = String::new();
  username_file.read_to_string(&mut username)?;
  Ok(username)
}

fn _learn_error0() {
  let r = match _error_back() {
    Ok(s) => println!("ro:{s}"),
    Err(e) => println!("re:{:?}", e),
  };
}

fn _error_back() -> Result<String, io::Error> {
  println!("before _error1");
  let e = _error1()?; // 这里返回err,就直接跳出了
  println!("after _error1");
  let o = _error0()?;
  Ok(o)
}

fn _error0() -> Result<String, io::Error> {
  println!("_error0");
  Ok(String::from("hello"))
}
use std::error;

fn _error1() -> Result<bool, io::Error> {
  println!("_error1");
  Err(io::Error::from(io::ErrorKind::NotFound))
}

fn _learn_opt() {
  let r = match _opt_back() {
    Some(i) => println!("op:{i}"),
    None => println!("op:none"),
  };
}

fn _opt_back() -> Option<u8> {
  let a = _opt0()?;
  println!("after some,before none");
  let b = _opt1()?; // 这里返回None,就直接跳出了
  println!("after none");
  Some(a)
}

fn _opt0() -> Option<u8> {
  println!("some");
  Some(1)
}
fn _opt1() -> Option<u8> {
  println!("none");
  None
}
